const linkurl = 'http://bylm.zxinvest.cn/api/h5/';
const linkurl2 = 'http://bylm.zxinvest.cn/';


// 获取Storage
function GetStorage(name) {
	var _value = uni.getStorageSync(name);
	return _value;
};

// 返回当前 接口链接
function CommLink() {
	return linkurl2;
};

function http(method, url, param, CallBack, num) {
	var that = this;
	param = param && typeof param === 'object' ? param : {};
	let token = GetStorage('byh5token');
	if (token) {
		var headers = {
			"Authorization": 'Bearer ' + token,
			'Content-Security-Policy': 'self',
			'X-Content-Type-Options': 'nosniff',
			'Content-Type': 'application/json'
		};
	} else {
		var headers = {
			'Content-Security-Policy': 'self',
			'X-Content-Type-Options': 'nosniff',
			'Content-Type': 'application/json'
		};
	}
	uni.request({
		// url: '/api/' + url,
		url: linkurl + url,
		method: method,
		data: param,
		responseType: num ? 'arraybuffer' : 'json',
		header: headers,
		success: (res) => {
			uni.hideLoading();
			if (res.statusCode == 401) {
				if (IsWechat()) {
					uni.showToast({
						icon: 'none',
						title: '登录已过期，正在重新登录...',
						duration: 2000
					});
					uni.removeStorage({
						key: 'byh5token',
						success: function(res) {
							console.log('success');
						}
					});
					uni.removeStorage({
						key: 'byh5type',
						success: function(res) {
							console.log('success');
						}
					});
					uni.removeStorage({
						key: 'byh5token',
						success: function(res) {
							console.log('success');
						}
					});
					uni.removeStorage({
						key: 'byopenid',
						success: function(res) {
							console.log('success');
						}
					});

					var _url = 'http://bylm.zxinvest.cn/h5#/';
					window.location.href =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx94b6f3a9e0b140cf&redirect_uri=' +
						encodeURIComponent(_url) +
						'&response_type=code&scope=snsapi_userinfo&agentid=9&state=BYLM#wechat_redirect';

				} else {
					uni.showToast({
						icon: 'none',
						title: '登录已过期，请重新登录',
						duration: 2000
					});
					setTimeout(function() {
						uni.reLaunch({
							url: '/pages/login/login',
						})
					}, 1500);
				}
			} else {
				if (url == 'register') {
					CallBack(res.data);
				} else {
					if (res.data.code == 200) {
						CallBack(res.data);
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg,
							duration: 2000
						});
					}
				}
			}
		},
		fail: function(res) {
			uni.hideLoading();
			console.log(res);
		},
	});
};


// 上传图片
function UploadPic(data, CallBack) {
	let token = GetStorage('byh5token');
	var headers = {
		"Authorization": 'Bearer ' + token
	};
	console.log(data)
	uni.uploadFile({
		url: linkurl + 'upload',
		fileType: 'image',
		filePath: data,
		header: headers,
		name: 'file',
		formData: {
			type: 'file'
		},
		success: (res) => {
			CallBack(res.data)
		}
	});
};





// 下载
function DownFile(url, CallBack) {
	let token = GetCookie('token').replace(/"/g, '');
	uni.downloadFile({
		url: url, //仅为示例，并非真实的资源 // 根据业务修改header 
		header: {
			"Authorization": 'Bearer ' + token,
			'token': token
		},
		success: (res) => {

			CallBack(res);
		}
	});
};




//时间戳转时间
function FormatDate(date, withTime = false) {
	var date = new Date(date);
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var formattedDate = Y + M + D;

	if (withTime) {
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
		var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		formattedDate += ' ' + h + m + s;
	}

	return formattedDate;
}





function GetCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i].trim();
		if (c.indexOf(name) == 0) {
			var cookieValue = c.substring(name.length, c.length);
			cookieValue = cookieValue.replace(/"/g, ""); // 去掉引号
			return cookieValue;
		}
	}
	return "";
};

function SetCookie(cName = '', cValue = '', exdays = '0.3') {
	var exdate = new Date() // 获取时间
	exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
	// 字符串拼接cookie
	window.document.cookie = cName + '=' + JSON.stringify(cValue) + ';path=/;expires=' + exdate.toGMTString()
};

function ClearCookie(name) {
	SetCookie(name, '', -1)
};

function Down(method, url, param, name, CallBack) {
	var that = this;
	param = param && typeof param === 'object' ? param : {};
	let token = GetStorage('token');
	if (token) {
		var headers = {
			'Token': token
		};
	} else {
		var headers = {};
	}
	uni.request({
		url: linkurl + url,
		method: method,
		data: param,
		responseType: 'arraybuffer',
		header: headers,
		success: (response) => {
			console.log(response)
			uni.hideLoading();
			if (response.statusCode == 200) {
				const url = URL.createObjectURL(new Blob([response.data]));
				const a = document.createElement('a');
				a.href = url;
				a.download = name;
				a.click();
				URL.revokeObjectURL(url);
			} else if (res.statusCode == 401) {

			}
		}
	});
};

function GetNowTime() {
	const today = new Date();
	const year = today.getFullYear();
	const month = String(today.getMonth() + 1).padStart(2, '0');
	const day = String(today.getDate()).padStart(2, '0');
	const currentDate = `${year}-${month}-${day}`;
	return currentDate;
};


function getNextDate(years) {
	const currentDate = new Date()
	const currentYear = currentDate.getFullYear()
	const currentMonth = currentDate.getMonth() + 1 // 月份从0开始，所以需要加1
	const currentDay = currentDate.getDate()

	let nextYear = currentYear
	let nextMonth = currentMonth
	let nextDay = currentDay

	if (years !== 0) {
		nextYear = currentYear + years
	}

	return `${nextYear}-${nextMonth.toString().padStart(2, '0')}-${nextDay.toString().padStart(2, '0')}`
};

function getDateOneYearLessOneDay() {
	const currentDate = new Date();
	const nextYear = currentDate.getFullYear() + 1;
	const nextYearDate = new Date(nextYear, currentDate.getMonth(), currentDate.getDate() - 1);	
	return DateToString(nextYearDate).slice(0, 10);
};

function DateToString(dateString) {
	const date = new Date(dateString);

	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	const seconds = String(date.getSeconds()).padStart(2, '0');

	const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	return formattedDate;
};



function IsWechat() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		console.log('是微信客户端')
		return true;
	} else {
		console.log('不是微信客户端')
		return false;
	}
};







export default {
	GetStorage: GetStorage,
	http: http,
	FormatDate: FormatDate,
	GetCookie: GetCookie,
	CommLink: CommLink,
	SetCookie: SetCookie,
	ClearCookie: ClearCookie,
	DownFile: DownFile,
	Down: Down,
	GetNowTime: GetNowTime,
	UploadPic: UploadPic,
	getNextDate: getNextDate,
	DateToString: DateToString,
	IsWechat: IsWechat,
	getDateOneYearLessOneDay: getDateOneYearLessOneDay,
};